<?php

/*******************************************************************************
* 
* Poll4All::admin.php
* 
* Description: Admin panel.
*
* Author: C4F Team (http://code4fun.org)
*  
*******************************************************************************/

// Start or replace session
session_start();

/*
 * INCLUDE AND SETTING UP SOME VARIABLES
 */
include 'config.php';
include 'includes/functions.php';
require_once("includes/configmagik.php");

// Storage file path
$txtPath = "txt/txtdb.ini.php";
// Create and configure new ConfigMagik-Object
$dbTXT = new ConfigMagik( $txtPath, true, true);
$dbTXT->SYNCHRONIZE = false;
// Current script name
$currentFile= $_SERVER['SCRIPT_NAME'];

/*
 * Authentication
 */
// update session variables with "user name" and "password"
if ( isset($_POST['id']) && isset($_POST['pw']) ) {
     $_SESSION['userid']=$_POST['id']; $_SESSION['password']=$_POST['pw'];
}
// check "user name" and "password"
if ($_SESSION['userid']==$id && $_SESSION['password']==$pw ) {

// reset cookie must be sent before any output...
if ($_GET['flag']=='cookie' || $_GET['flag']=='del' || $_GET['flag']=='reset') { 
	setcookie( "poll4all", "", time()+1, "/");
}

// cookie check before any output
if ($_GET['flag']=='test') include 'check.php';	  

// print html header
top();

// control panel header
print_header();


/*
 * Start main loop
 */
switch ($_GET['flag']) {
        
/*
 * Create new poll or edit existing one
 */
case 'setup':
                
	// create new poll
	if ( isset($_POST['answers']) )  {

		$answers=$_POST['answers'];
        // Display form for options
        printAnswersForm($answers);
	}
    // edit poll
	else {
	
		$numAnswers = $dbTXT->get('numAnswers', 'MAIN');
		// Display form for options editing
        printAnswersForm($numAnswers, "edit");
	}
break; 

/*
 * Create poll
 */
case 'create':

	// ANSWERS
	$array_answers = $_POST['array_answers'];
    // text adjustment
    for ($i=0; $i<count($array_answers); $i++) rectifyText($array_answers[$i]);

	// QUESTION 
	$question=trim($_POST['question']);
	// text adjustment
    rectifyText($question);

	// VALIDATE POLL
	if ($errorMsg=validatePoll($array_answers,$question)) {

    	// SHOW ERRORS FOUND
        echo "<div class=\"box\">
              <div class=\"title\">Error :</div>
			   $errorMsg
              </div>";

		printAnswersForm(count($array_answers), $_POST['action']);
	}

	// NO ERRORS FOUND: CREATE NEW POLL
    else {
		
		newPoll($array_answers,$question);
				
		// Save on file
        if ($dbTXT->save()) success("Poll created successfully!");
        else print "Error: write to file failed<br />";
	}
break;

/*
 * Update poll.
 */
case 'update':
		
	$array_answers = $_POST['array_answers'];	// answers
	// text adjustment
    for ($i=0; $i<count($array_answers); $i++) rectifyText($array_answers[$i]);

	$question = trim($_POST['question']);		// question
    rectifyText($question);					    // text adjustment

	// validate poll
	if ($errorMsg=validatePoll($array_answers,$question)) {

	    // show errors found
        echo "<div class=\"box\">
              <div class=\"title\">Error :</div>
			   $errorMsg
              </div>";

         printAnswersForm(count($array_answers), "edit");
	}
	
	// no errors found: update poll
	else {
		// update poll (no votes reset)
		updatePoll($array_answers, $question);
				
		// save on file
        if ($dbTXT->save()) success("Poll updated successfully!");
        else print "Error: write to file failed<br />";
	}
break;

/*
 * Display control panel
 */
case 'cp':

	// Print current poll if exist
    if($dbTXT->get('pollid','MAIN')!=null) {
                        
		print "<div align=\"center\"><p>";
		pollPrint($dbTXT);
		print "</p></div>";
				  
		// Print extra options
		extraMenu();
	}
    else {
    
        echo "<div class=\"boxHeader\">
		      <div class=\"cBox\">No poll, click \"<a href='$currentFile?flag=wizard'>new poll</a>\" to create one.</div>
		      </div>";
	}
break; 
                
/*
 * Erase current poll.
 */
case 'del':
	
    $dbTXT->removeSection('MAIN');
	$dbTXT->removeSection('ANSWERS');
	if ($dbTXT->save()) {
	    
	    echo  "<div class=\"cBox\">
			  <p>
	          <span class=\"text\"><strong>&gt;&gt; Poll deleted &lt;&lt;</strong></span>
	          </p>
	          [ <a href='$currentFile?flag=cp'>go back</a> ]
			  </div>";		
	
	}
	else print "Error: erase poll failed<br />";
break;

/*
 * Reset poll votes
 */
case 'reset':

	resetVotes();
	// save on files
    if ($dbTXT->save()) {
	    echo  "<div class=\"cBox\">
			  <p>
	          <span class=\"text\"><strong>&gt;&gt; Reset successful &lt;&lt;</strong></span>
	          </p>
	          [ <a href='$currentFile?flag=cp'>go back</a> ]
			  </div>";	
    }
    else print "Error: write to file failed<br />";
                      
break;

/*
 * New poll wizard
 */
case 'wizard':
                        
	echo "<div class=\"box\">
          <form name=\"poll\" method=\"post\" action=\"$currentfile?flag=setup\">
		  <div class=\"title\">.: New Poll Wizard [step 1/2]</div>
		  <div class=\"cBox\">
		  <span class=\"text\">Select number of answers :</span>&nbsp;<select name=\"answers\">";
	for ($i=2; $i<8; $i++) print "<option value=$i>$i</option>";
    echo "</select>
		  &nbsp;&nbsp;
		  <input type=\"submit\" name=\"submit\" value=\"Go Ahead &gt;&gt;\">
		  </div>
          </form></div>";

break;
                
/*
 * Poll test
 */               
case 'test':
      
	print "<div align=\"center\"><p>";
	poll();
	print "</p></div>";			
	extraMenu();	// show extra options

break;
		
/*
 * Reset cookie.
 */
case 'cookie':

  	echo "<div class=\"cBox\">
		  <p>
          <span class=\"text\"><strong>&gt;&gt; Cookie Reset Successful &lt;&lt;</strong></span>
          </p>
          [ Now you can <a href='$currentFile?flag=test'>vote again</a> ]
		  </div>";

	extraMenu();	// show extra options

break;
		
/*
 * Help
 */		
case 'help':
				
	echo "<div class=\"box\">
		  <div class=\"title\">.: help</div>
		  <div class=\"text\">
		  <strong>:: main menu</strong><br />
		  <ul>
		  <li><strong>new poll :</strong> create new poll, old poll will be overwritten</li>
		  <li><strong>view/edit :</strong> view (and edit) current poll.</li>
		  <li><strong>help :</strong> show this page.</li>
		  <li><strong>? :</strong> show author contact info.</li>
		  </ul>
		  <strong>:: extra options menu</strong><br />
		  <ul>
		  <li><strong>edit :</strong> edit question and/or answers poll, votes are not affected.</li>
		  <li><strong>reset votes :</strong> reset to \"0\" all votes.</li>
		  <li><strong>delete poll :</strong> erase current poll from database file.</li>
	      <li><strong>reset cookie :</strong> reset cookie on your browser so you can vote again.</li>
		  <li><strong>test poll :</strong> try yourself current poll. Warning: your test votes really affect the poll!</li>
		  </ul>
		  </div>
		  </div>";

break;
		
/*
 * About screen.
 */		
case 'about':
				echo "<div class=\"box\">
				      <div class=\"title\">.: about</div>
				      <div class=\"text\">
					  Poll4All is a <a href=\"http://code4fun.org\">Code4Fun</a> project.<br /><br />
					  Contact us @ <a href=\"mailto:info@code4fun.org\">info@code4fun.org</a>.<br /><br />
					  </div>
				      </div>";
break;
		
/*
 * Welcome screen.
 */
default:

	$msg="";

	echo "<div class=\"box\">
	      <div class=\"title\">WELCOME</div>";
    $msg.="Check database file...";
	
	if (file_exists($txtPath)) {
		
		$msg.="Ok<br />";
		$msg.="Check if is writable...";
		if (is_writable($txtPath)) $msg.="Ok<br />ALL OK!";
        else {
			
			$msg.="Ko<br />";
			$msg.="Try to change mode...";
			
			if (@chmod($txtPath, 0600)) $msg.="Ok<br />ALL OK!";
			else $msg.="Ko<br />Set the attributes of the file txtdb.ini.php to 666 (meaning read and write access for all parties).";
		}
	}
	else {
		
		$msg.="File doesn't exist.<br />";
 	    $msg.="Try to create it...";
	    if (@fopen($txtPath, "x+")) $msg.="Ok<br />";
  		else $msg.="Ko<br />File creation failed. Check if you have write permission for the directory.".$txtPath.".";
	}

	print "<div class=\"text\">$msg</div>";
	print "</div>";
	
}	// end switch 

foot();	// print xhtml footer

} // end authentication

/*
 * If check user name and password fail print restricted area form. 
 */ 
else {restrictedArea();}



/*******************************************************************************
*                          F U N C T I O N S                                 
*******************************************************************************/


/**
 * Print init form
 */
function print_header() {
	
	echo "<div class=\"boxHeader\">
          <!-- title -->
          <div class=\"logo\"><a href=\"http://code4fun.org\">Poll4All</a><br /><span class=\"text\">[v.1.2.1]</span></div>
          <!-- Menu -->
          <div class=\"menu\"><strong>.: MainMenu :</strong>&nbsp;&nbsp;<a href=\"$currentFile?flag=wizard\">new poll</a> | <a href=\"$currentFile?flag=cp\">view/edit current poll</a> | <a href=\"$currentFile?flag=help\">help</a> | <a href=\"$currentFile?flag=about\">?</a></div>
          </div>";
}

/**
 * Display the question/answer form
 * 
 * @param $num_answers		-	Number of poll answers
 * @param $option			-	new/edit
 */
function printAnswersForm($num_answers, $option="new") {

	global $currentFile,$dbTXT;

	// setting question value
	if ($option=="edit") {
		
		$questionValue = $dbTXT->get('question', 'MAIN');
		$flag='update';
		$title=".: Edit Current Poll";
	}
	else { $questionValue = ""; $flag='create'; $title=".: New Poll Wizard [step 2/2]";}
        
    echo "<div class=\"box\">
          <form name=\"init_poll\" method=\"post\" action=\"$currentFile?flag=".$flag."\">
		  <div class=\"title\">".$title."</div>
          <div class=\"answers\">Poll question :&nbsp;<input type=\"text\" size=\"61\" name=\"question\" value=\"".$questionValue."\"></div>
          <hr />";
                
	if ($option=="edit") print "<input type=\"hidden\" value=\"edit\" name=\"action\" />";

	/*
	 * Print answers input text
	 */ 
	for ($i=1; $i<=$num_answers; $i++) {

		// setting answer value
		$val="";
		if ($option=="edit") {
				
			$answerKey = "an".$i;
			$val = $answer = $dbTXT->get($answerKey,"ANSWERS");
		}
				
		print "<div class=\"answers\">.: answers [".$i."] :&nbsp;<input type=\"text\" size=\"61\" name=\"array_answers[]\" value=\"".$val."\"></div>";
	}
	
	// setting submit button value
	if ($option=="edit") $submitVal = ">> Update Poll <<";
	else $submitVal = ">> Create Poll <<";
    echo "<div class=\"cBox\"><input type=\"submit\" name=\"submit\" value=\"".$submitVal."\" /></div>
          </form></div>";
}


/**
 * Poll data validation
 * 
 * @param $answersArray		- Answers array
 * @param $question			- Poll question
 * @return zero if data is valid, error string if otherwise
 */
function validatePoll(&$answersArray, &$question) {

    $numErrors = 0;
    $msg = "";

    // Question validation
    if (!isset($question) || $question=="" ) {
    	$numErrors++;
        $msg.="Question can't be empty sentence!<br />";
	}

    // Check duplicated answers
    $array_no_doubles = array_unique($answersArray);
    if ( count($array_no_doubles)!=count($answersArray) ) {
    	$numErrors++;
        $msg.="Warning: Two or more answers are identical!<br />";
	}

	// Check for empty answers
    if (array_search( '' , $answersArray)!==false) {
    	$numErrors++;
        $msg.="Answers can't be empty sentences!<br />";
	}
    
    if (!$numErrors) return false;
    else return $msg;
}

/**
 * Rectify text from special characters
 * 
 * @param String $string		- Text to rectify
 */
function rectifyText(&$string) {
	
	$string = str_replace("\\'","'",$string);
	$string = str_replace('\"',"&quot;",$string);
	$string = str_replace("<", "&lt;", $string);
	$string = str_replace(">", "&gt;", $string);
}

/**
 * Create new poll.
 * 
 * @param $answers		- Answers array
 * @param $question		- Poll question
 */
function newPoll(&$answers, &$question) {

	global $currentFile,$dbTXT;
	
	// gets new poll id (timestamp)
	$pollid=time();
	$dbTXT->set('pollid', $pollid, 'MAIN');

	updatePoll($answers,$question);
	
	resetVotes();
}


/**
 * Update answers or questions without affecting votes' count
 * 
 * @param $answers		- New aswers array
 * @param $question		- New poll question
 */
function updatePoll(&$answers, &$question) {

	global $currentFile,$dbTXT;
	$oldNumAnswers = $dbTXT->get('numAnswers', 'MAIN');
	$numAnswers = count($answers);

	// update poll question
    $dbTXT->set('question', $question, 'MAIN');
    $dbTXT->set('numAnswers', $numAnswers, 'MAIN');

	// update answers
	for ($i=0; $i<$numAnswers; $i++) {

		rectifyText($answers[$i]);
		$answerKey = "an".($i+1);
		$dbTXT->set($answerKey, $answers[$i], 'ANSWERS');
	}
    
    if ( ($oldNumAnswers - $numAnswers) > 0 ) {
		for ($i=($numAnswers+1); $i<=$oldNumAnswers; $i++) {
    	    $answerKey = "an".$i;
			$pollKey = "an".$i."poll";
			$dbTXT->removeKey($answerKey, 'ANSWERS');
			$dbTXT->removeKey($pollKey, 'ANSWERS');
		}
    }        
}


/**
 * Display confirmation for successful poll creation
 * 
 * @param String $msg		- Message text
 */
function success($msg) {

	echo "<div class=\"box\">
	      <div class=\"cBox\">
          <span class=\"text\"><strong>".$msg."</strong></span><br />
	      <p>[<a href='$currentFile?flag=test'> TEST POLL </a>]</p>
	      </div>";
}

/**
 * Reset votes
 */
function resetVotes() {

	global $currentFile,$dbTXT;
        
	$numAnswers = $dbTXT->get('numAnswers', 'MAIN');
	
    for ($i=1; $i<=$numAnswers; $i++) {
		$pollKey = "an".$i."poll";
		$dbTXT->set($pollKey, 0, 'ANSWERS');
	}
}

/**
 * Print the extra menu (edit, reset votes, delete poll, reset cookie, test poll)
 */
function extraMenu() {	
		
	echo "<p>
          <div class=\"extraMenu\">
          <strong>.: extra options :</strong>
          <span class=\"text\">
          <a href='$currentFile?flag=setup&action=edit'>edit</a>&nbsp;|&nbsp;
          <a href='$currentFile?flag=reset'>reset votes</a>&nbsp;|&nbsp;
	      <a href='$currentFile?flag=del'>delete poll</a>&nbsp;|&nbsp;
          <a href='$currentFile?flag=cookie'>reset cookie</a>&nbsp;|&nbsp;
          <a href='$currentFile?flag=test'>test poll</a>&nbsp;
          </span>
          </div>
          </form>
	      </p>";
}

/**
 * Login form              
 */
function restrictedArea() {

	echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
          <html xmlns=\"http://www.w3.org/1999/xhtml\">
          <head>
          <title>Poll4All Restricted Area</title>
          <meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\" />
          <style type=\"text/css\">
          <!--
			body {
     		     background-color: #FFFFFF;
                 margin-top: 30px;
                 margin-right: 0px;
                 margin-bottom: 0px;
                 margin-left: 0px;
                 font-family: Verdana, Arial, Courier, Serif;
			}

			.container { margin:0px auto; text-align: center; width: 200px;}
			.box {
					background-color: #CCCCCC;
					width: 200px;
					text-align: center;
					border-color: #000000;
					border-style: solid;
					border-width: 2px 2px 2px 2px;
					padding: 10px 4px 4px 4px;
					margin: 0px 0px 0px 0px;
					font-family: Verdana, Arial, sans-serif;
					font-size: 13px;
			}
            -->
            </style>
            </head>
            <body>
            <div align=\"center\">
			<div class=\"container\">
			<div class=\"box\">
			<p><strong>Poll4All</strong><br />Restricted Area</p>
			<form name=\"restricted\" action=\"$currentFile\" method=\"post\">
			User Name: <input name=\"id\" type=\"text\" value=\"\" /><br />
			Password: <input name=\"pw\" type=\"password\" value=\"\" />
			<p><input type=\"submit\" value=\"submit\" /></p>
			</form>
			</div>
			</div>
			</div>
			</body>
			</html>";
}


/**
 * Print header.
 */
function top() {

	echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
      		<html xmlns=\"http://www.w3.org/1999/xhtml\">
       		<head>
	        <title>Poll4All - Code4Fun.org</title>
	        <meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\" />
	        <style type=\"text/css\">
	        <!--
	        body { background:#F3F3F1; margin-top: 30px; font-family: Arial, Verdana, sans-serif; color: #000000; font-size: 12px; padding:0px;}
	        .container { margin:0px auto; width: 500px;}
	        A:LINK {text-decoration:none; color: #000000;}
	        A:VISITED {text-decoration:none; color: #000000;}
	        A:HOVER {text-decoration:none; color: #BB381A;}
        
        	.boxHeader { padding: 0px; width: 500px; border-style: dashed; border-width: 1px;}
        	.box       { padding: 20px 5px 5px 5px; width: 490px; border-style: solid; border-width: 0px 1px 1px 1px; }
			.cBox      { font-size: 12px; padding: 10px 5px; text-align:center;}
			.logo      { background:#EFF0D8; font-size: 26px; font-style: bold; font-family: Verdana,Arial, sans-serif; text-align: center; padding: 10px 5px; border-style: dashed; border-width: 0px 0px 1px 0px;}
			.menu      { background:#EFF0D8; font-size: 12px; font-family: Verdana,Arial, sans-serif; text-align:left; padding: 5px; }
        	.title    { font-size: 12px; font-family: Verdana,Arial, sans-serif; font-weight: bold; text-align:left;  border-style: dashed; border-width: 0px 0px 1px 0px; padding : 0px 5px 2px 5px; margin-bottom: 10px;}
        	.text     { font-size: 12px; font-family: Verdana,Arial, sans-serif; text-align:left; padding: 5px;}
			.answers   { padding: 5px 0px 5px 2px;}
        	.extraMenu { background:#EFF0D8; font-size: 13px; font-family: Arial,Verdana, sans-serif; padding: 5px; text-align:left; width: 490px; border-style: dashed; border-width: 1px;}
			hr         { border: 0; width: 100%; height: 2px; color: #CCCCCC; background-color: #CCCCCC; }
        
       		-->
        	</style>
        
       		</head>
        	<body>
        	<div class=\"container\">";
}


/**
 * Print footer.
 */
function foot() { echo "</div></body></html>"; }

?>
